package com.sq.partner.manager.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.sq.partner.manager.common.Constants;
import com.sq.partner.manager.common.Result;
import com.sq.partner.manager.mybatis.model.GatewayRole;
import com.sq.partner.manager.mybatis.model.GatewayUser;
import com.sq.partner.manager.mybatis.model.GatewayUserRole;
import com.sq.partner.manager.service.IGatewayUserService;
import com.sq.partner.manager.util.LogUtil;
import com.sq.partner.manager.util.MD5Util;
import com.sq.partner.manager.util.Page;
import com.sq.partner.manager.util.PasswordUtil;
import com.sq.partner.manager.util.StrUtil;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;

/**
 * 用户管理Controller
 * @author zhihuizhao
 *
 */
@Controller
@RequestMapping(value = "/systemManager")
public class GatewayUserController {
	
	private static Logger logger = LogUtil.getLog(GatewayUserController.class);
	
	@Resource
	private IGatewayUserService userService;

	@RequestMapping(value="/userManagement")
	public String showUserList(Model model) throws Exception
	{
		return "systemManager/userManage";
	}

	/**
	 * 页面初始化加载所有用户列表
	 * @param size
	 * @param pageIndex
	 * @param user
	 * @param userName
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="/userManagement/initAllUsers")
	public @ResponseBody Page initAllUsers(Integer size,Integer pageIndex,GatewayUser user,String userName,String userCode,HttpSession session) throws Exception
	{
		GatewayUser u = (GatewayUser)session.getAttribute(Constants.SESSION_USER);
		Map<String,String> param = new HashMap<String,String>();
		if(StrUtil.isNotEmpty(userName)){
			param.put("userName", userName);
		}
		if(StrUtil.isNotEmpty(userCode)){
			param.put("userCode", userCode);
		}
		Page page=new Page();
		page.setCurrent(pageIndex);
		Page p = userService.queryPage(page,pageIndex,param,u);
		return p;
	}

	/**
	 * 选择某一个用户删除时，根据其ID进行删除操作
	 * @param user
	 * @param userID
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="/userManagement/delUser")
	public @ResponseBody Result delUserById(Long userid,GatewayUserRole ur) throws Exception{
		if(StrUtil.isEmpty(String.valueOf(userid))){
			return Result.error("无法选择该用户，请联系管理员");
		}else{
			userService.delUserById(userid);
			ur.setUserid(userid);
			userService.delUserRoleUserid(userid);
			return Result.success("删除成功");
		}
	}
	
	
	/**
	 * 查询用户信息
	 * @param userid
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="/userManagement/editUser")
	public @ResponseBody GatewayUser queryUserById(Long userid) throws Exception{
			return userService.queryUserById(userid);
	}
	
	/**
	 * 根据用户在界面输入内容保存修改
	 * @param req
	 * @param user
	 * @param userid
	 * @param username
	 * @param email
	 * @param usercode
	 * @param telephone
	 * @param status
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="/userManagement/saveUser")
	public @ResponseBody Result saveUser(HttpServletRequest req,GatewayUser user,Long userid,String username,String email,String usercode,String telephone,Integer status) throws Exception{
			user.setUserCode(usercode);
			user.setUserName(username);
			user.setEmail(email);
			user.setTelephone(telephone);
			user.setStatus(status);
			user.setOperUser(getSessionUser(req).getUserid());
			user.setUserid(userid);
			
			user.setOperTime(getCurdate());
			boolean flag = userService.saveUser(user);
			if(flag==false){
				return Result.error("修改失败，请联系管理员");
			}else{
				return Result.success("修改成功");
			}
	}
	
	
	/**
	 * 跳转至修改密码页面
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="/showModifyPwd")
	public String show() throws Exception {
		return "systemManager/modifyPwd";
	}

	
	/**
	 * 修改密码
	 * @param req
	 * @param user
	 * @param userid
	 * @param oldPwd
	 * @param newPwd
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="/userManagement/modifyPwd")
	public @ResponseBody Result modifyPwd(HttpServletRequest req,GatewayUser user,String oldPwd,String newPwd,String sureNewPwd) throws Exception{
		//首先校验旧密码
		if(StrUtil.isEmpty(oldPwd)){
			return Result.error("旧密码不能为空");
		}
		//校验新密码
		if(StrUtil.isNotEmpty(newPwd)){
			if(!PasswordUtil.checkPassword(newPwd)){
				return Result.error("新密码复杂度较低，必须包含 数字、字符、特殊字符[!@#$%^&*?]");
			}
		}else{
			return Result.error("新密码不能为空");
		}
		//校验确认密码
		if(StrUtil.isNotEmpty(sureNewPwd)){
			if(!newPwd.equals(sureNewPwd)){
				return Result.error("确认密码和新密码不一致");
			}
		}else{
			return Result.error("确认新密码不能为空");
		}

		//先获取用户的旧密码，再跟用户输入的旧密码进行MD5加密后的内容 比较
		GatewayUser u = getSessionUser(req);
		user = userService.queryUserById(u.getUserid());
		if(StrUtil.isNotEmpty(oldPwd) && user.getUserPwd().equals(MD5Util.md5(oldPwd))){
			user.setUserid(u.getUserid());
			user.setUserPwd(MD5Util.md5(newPwd));
			if(userService.modifyPwd(user)){
				logger.info("=================密码修改成功==================");
				return Result.success("密码修改成功");
			}else{
				return Result.error("密码修改失败");
			}
		}else{
			return Result.error("旧密码输入有误，请重新输入");
		}
	}
	
	
	/**
	 * 获取某个用户所拥有的角色
	 * @param req
	 * @param userrole
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="/userManagement/getUserRole")
	public @ResponseBody List<GatewayRole> getUserRole(HttpServletRequest req,Long userid) throws Exception {

		List<GatewayRole> list = userService.getUserRole(userid);
		return list;
	}
	

	/**
	 * 添加用户之前，校验用户名是否已经存在，是就提示输入的用户名已存在，重新输入；
	 * 否就判断是否已经在UM系统中配置该用户，没有配置提示先在UM系统中配置此用户再进行操作，
	 * 已经进行配置过的直接添加。
	 * @param req
	 * @param user
	 * @param usercode
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="/userManagement/checkUserCodeIsExists")
	public @ResponseBody Result addUser(HttpServletRequest req,GatewayUser user,String usercode) throws Exception {
		Map<String,String> map = new HashMap<String, String>();
		map.put("userCode", usercode);
		GatewayUser ur = (GatewayUser)userService.queryUserCount(map);
		if(ur!=null){
			logger.info("---------------用户名已存在------------------");
			return Result.error("该用户名已存在");
		}else{
			return null;
		}
	}
		
		/**
	 * 添加用户  输入的用户名如果系统中已存在，则提示信息，重新输入
	 * @param user
	 * @param username
	 * @param email
	 * @param usercode
	 * @param telephone
	 * @param status
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="/userManagement/addUser")
	public @ResponseBody Result addUser(HttpServletRequest req,GatewayUser user,String username,String email,String usercode,String telephone,Integer status) throws Exception {
		Map<String,String> map = new HashMap<String, String>();
		GatewayUser uu = new GatewayUser();
		uu.setUserCode(usercode);
		map.put("userCode", uu.getUserCode());
		GatewayUser ur = (GatewayUser)userService.queryUserCount(map);
		if(ur!=null){
			logger.info("---------------用户名已存在------------------");
			return Result.error("该用户名已存在");
		}else
		{
			String password = PasswordUtil.getPassword();
			user.setUserPwd(MD5Util.md5(password));
			user.setUserCode(usercode);
			user.setUserName(username);
			user.setEmail(email);
			user.setTelephone(telephone);
			user.setStatus(new Integer(1));
			user.setOperUser(getSessionUser(req).getUserid());
			user.setOperTime(getCurdate());
			
			if(userService.addUser(user)){
				logger.info("添加用户成功,初始密码是:<a style=\"color:red\">"+password+"</a>请牢记!");
				return Result.success("添加成功,初始密码是:<a style=\"color:red\">"+password+"</a>请牢记!");
			}else{
				logger.info("添加用户失败");
				return Result.error("添加失败");
			}
			
		}
	}
	
	
	
	/**
	 * 查询所有角色
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="/userManagement/getAllRoles")
	public @ResponseBody List<GatewayRole> setRoleToUser(HttpSession session) throws Exception{
		GatewayUser u = (GatewayUser)session.getAttribute(Constants.SESSION_USER);
		List<GatewayRole> list = userService.queryAllRolesByUser(u);
		if(list!=null){
			return list;
		}else{
			return new ArrayList<GatewayRole>();
		}
	}
	
	@RequestMapping(value="/userManagement/queryRolesPageByUser")
	public @ResponseBody Page queryRolesPageByUser(Integer size,Integer pageIndex,String deptCode,String roleName,HttpSession session,String currentUserId) throws Exception{
		GatewayUser u = (GatewayUser)session.getAttribute(Constants.SESSION_USER);
		Map<String,String> param = new HashMap<String,String>();

		if(StrUtil.isNotEmpty(currentUserId)){
			param.put("userId", currentUserId);
		}
		if(StrUtil.isNotEmpty(deptCode)){
			param.put("deptCode", deptCode);
		}
		if(StrUtil.isNotEmpty(roleName)){
			param.put("roleName", roleName);
		}
		Page page=new Page();
		page.setSize(size);
		page.setCurrent(pageIndex);
		Page p = userService.queryRolesPageByUser(page,pageIndex,param,u);
		return p;
	}
	
	@RequestMapping(value = "/userManagement/queryDeptCode",method = RequestMethod.POST)
    public @ResponseBody Result queryDeptCode(HttpSession session) throws Exception {
		GatewayUser user=(GatewayUser) session.getAttribute(Constants.SESSION_USER);
		logger.info("当前登录用户的userCode为"+user.getUserCode()+",DepartmentStr:"+user.getDepartmentStr());
		
		if(null != user && StrUtil.isNotEmpty(user.getDepartmentStr())){
			return Result.data(userService.queryDeptCode(user));
		}
		
		return Result.fail();
    }
	/**
	 * 给用户设置角色
	 * @param role
	 * @param userid
	 * @param roleidStr
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="/userManagement/setRole")
	public @ResponseBody Result setRoleToUser(HttpServletRequest req,GatewayUserRole role,Long userId,String userRoleListStr) throws Exception{
		if(userId==null){
			userId=(long)-1;
		}
		role.setUserid(userId);
		if(StrUtil.isNotEmpty(userRoleListStr)&&!"''".equals(userRoleListStr)){
			userService.removeAllRolesFromUser(userId);
			String ids="";
			if(!StrUtil.isEmpty(userRoleListStr)){
				//创建一个JsonParser
				JsonParser parser = new JsonParser();
				//通过JsonParser对象可以把json格式的字符串解析成一个JsonElement对象
				JsonElement el = parser.parse(userRoleListStr);
				//把JsonElement对象转换成JsonArray
				JsonArray jsonArray = null;
				if(el.isJsonArray()){
					jsonArray = el.getAsJsonArray();
				}
				for (JsonElement jsonElement : jsonArray) {
					String id =jsonElement.getAsJsonObject().get("id").getAsString();
					ids= ids+id+",";
				}
				if(ids.length()>0){
					ids=ids.substring(0, ids.length()-1);
				}
			}
			String[] roleArr = ids.split(",");
			boolean flag =true;
			for(int i=0;i<roleArr.length;i++){
				GatewayUserRole ur = new GatewayUserRole();
				ur.setUserid(userId);
				ur.setRoleid(Long.parseLong(roleArr[i]));
				ur.setOperUser(getSessionUser(req).getUserid());
				ur.setOperTime(getCurdate());
				flag = userService.setRoleToUser(ur);
				if(!flag){
					break;
				}
			}
			if(flag){
				return Result.success("设置成功");
			}else{
				return Result.success("设置失败");
			}
		}else{
			userService.removeAllRolesFromUser(userId);
			return Result.success("用户角色重置成功");
		}
	}
	

	
	/**
	 * 重置密码
	 * @param user
	 * @param userid
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="/userManagement/resetPwd")
	public @ResponseBody Result resetPassword(GatewayUser user,Long userid) throws Exception {
		user.setUserid(userid);
		String password = PasswordUtil.getPassword();
		user.setUserPwd(MD5Util.md5(password));
		boolean flag = userService.modifyPwd(user);
		if(flag){
			return Result.success("密码重置成功，密码是:<a style=\"color:red\">"+password+"</a><br>请通知该用户尽快修改密码");
		}else{
			return Result.error("密码重置失败");
		}
	}
	/**
	 * 获取系统当前时间
	 * @return
	 * @throws Exception
	 */
	public static Date getCurdate() throws Exception{
		Date dt = new Date();
		return dt;
	}
	
	/**
	 * 获取session中的User
	 * @param req
	 * @return
	 */
	public static GatewayUser getSessionUser(HttpServletRequest req){
		HttpSession session = req.getSession();
		GatewayUser u = (GatewayUser)session.getAttribute(Constants.SESSION_USER);
		return u;
	}

}
